package partFour.homeWork.code.Code04;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * 基于TCP实现客户端业务逻辑
 */
public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        try {
            // 1 建立连接
            socket = new Socket("127.0.0.1", 8808);
            System.out.println("连接服务器成功！");

            // 2 传输数据
            out = new ObjectOutputStream(socket.getOutputStream());
            out.writeObject(new UserMessage("check",new User("admin","122222")));

            // 2.1获取从客户端返回的数据
            in = new ObjectInputStream(socket.getInputStream());
            UserMessage reponseInfo = (UserMessage) in.readObject();

            // 2.2 判断登录是否成功
            String info  = reponseInfo.getType();
            if ("success".equals(info) ){
                System.out.println("登录成功！");
            }else if ("fail".equals(info)){
                System.out.println("登录失败！");
            }else {
                System.out.println("未知！");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            //  3关闭各种流
            if (null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
